import http from '@/api/http.js'
import store from '@/store/index.js'

const requestUserInfo = function(code, encryptedData, iv, user_info, obj, url){
	let params = {
		method: 'api/v2/member_login/login_by_mini_program',
		code,
		encryptedData,
		iv,
		user_info
	}
	http(params).then(res => {
		if(res.status){
			uni.setStorageSync('nickname', user_info.nickName);
			uni.setStorageSync('headimg', user_info.avatarUrl);
			uni.setStorageSync('session_key', res.data.wx_data.session_key);
			uni.setStorageSync('openid', res.data.wx_data.openid);
			let unionid = res.data.wx_data.unionid ? res.data.wx_data.unionid : '';
			uni.setStorageSync('unionid', unionid);
			if(res.data.token){
				uni.hideLoading();
				store.commit('login', res.data.memberInfo);
				uni.setStorageSync('token', res.data.token);
				uni.setStorageSync('userInfo', res.data.memberInfo);
				// obj.userInfo = {...res.data.memberInfo};
				// obj.isLogin = obj.$store.state.hasLogin;
				if(url){
					if(url =="/pages/ucenter/index"){
						uni.switchTab({
							url: url
						})
					}else{
						uni.redirectTo({
							url: url
						})
					}
				}else{
					let pages = getCurrentPages();
					let prev = pages[pages.length - 2];
					if(prev){
						setTimeout(() => {
							uni.navigateBack()
						}, 200)
					}else{
						setTimeout(() => {
							uni.switchTab({
								url: "/pages/index/home"
							})
						}, 200)
					}
				}
			}else{
				uni.hideLoading();
				uni.navigateTo({
					url: '/platforms/mp-weixin/login/authorize'
				})
			}
		}
	})
};

export default function(obj, url){
	let code;
	uni.login({
		provider: "weixin",
		success: (loginRes) => {
			if(loginRes.errMsg === 'login:ok'){
				code = loginRes.code
			}
			uni.showModal({
				title: '提示',
				content: '该操作需要获取您的用户信息',
				success(conRes) {
					if(conRes.confirm){
						wx.getUserProfile({
							desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
							success: (res) => {
								uni.showLoading({
									title: '登录中...'
								})
								requestUserInfo(code, res.encryptedData, res.iv, res.userInfo, obj, url)
							}
						})
					}
				}
			})
		}
	})
}